package com.bbs.service;

import java.util.ArrayList;
import java.util.List;

import com.bbs.dao.ArticleDao;
import com.bbs.dao.BlocksDao;
import com.bbs.dao.ModeratorDao;
import com.bbs.entity.Article;
import com.bbs.entity.Blocks;
import com.bbs.entity.Moderator;
import com.bbs.util.Page;

public class BlocksService {
	
	private BlocksDao blocksDao = new BlocksDao();
	private ArticleDao articleDao = new ArticleDao();

	/**
	 * 找到所有的父板块，包括子版块及其板块下的最新帖子
	 * @return List<Blocks>
	 */
	public List<Blocks> findAll() {
		List<Blocks> list = blocksDao.findFatherBlocks();
		List<Blocks> newList = new ArrayList<Blocks>();
		
		for(Blocks b : list) {
			List<Blocks> b2List = blocksDao.findByBlocksPid(b.getId());
			if(b2List != null) {
				List<Blocks> b3List = new ArrayList<Blocks>();
				for(Blocks b2: b2List) {
					b2.setArticle(articleDao.findNewArticle(b2.getId()));
					b3List.add(b2);
				}
				
				b.setBlocksList(b3List);
			}
			newList.add(b);
		}
		return newList;
	}
	
	/**
	 * 找出所有子版块
	 * @return
	 */
	public List<Blocks> findZBlocks(){
		return new BlocksDao().findZBlocks();
	}
	
	/**
	 * 找到一个板块及其下所有的帖子
	 * @param id
	 * @return
	 */
	public Blocks findById(String id) {
		Blocks b = blocksDao.findById(Integer.parseInt(id));
		b.setAlist(articleDao.findByBid(Integer.parseInt(id)));
		return b;
	}
	
	public Blocks findByIdAndPage(String id, Page page) {
		Blocks b = blocksDao.findById(Integer.parseInt(id));
		b.setAlist(articleDao.findByBidAndPage(Integer.parseInt(id),page));
		
		return b;
	}
	
	/**
	 * 找到所有的父板块，包括子版块及其板块下的帖子和版主
	 * @return List<Blocks>
	 */
	public List<Blocks> findBlockslist(){
		List<Blocks> blist = new BlocksDao().findFatherBlocks();
		List<Blocks> newBList = new ArrayList<Blocks>();
		for(Blocks b : blist){
			List<Blocks> bblist = new BlocksDao().findByBlocksPid(b.getId());
			List<Blocks> newList = new ArrayList<Blocks>();
			for(Blocks bb : bblist){
				List<Article> alist = new ArticleDao().findByBid(bb.getId());
				List<Moderator> mlist = new ModeratorDao().findByBid(bb.getId());
				bb.setAlist(alist);
				bb.setMlist(mlist);
				bb.setArticleNum(alist.size());
				newList.add(bb);
			}
			b.setBlocksList(newList);
			newBList.add(b);
		}
		return newBList;
	}

	public int getCount(int id) {
		
		return blocksDao.findBlocksCount(id);
	}

	public void deleteById(int id) {
		blocksDao.deleteById(id);
	}
}
